$(function () {
  let userid = null;
  let cart_goods_data;
  function getCartData(user_id) {
    let data_cart = [];
    $.ajax({
      url: "/api/cart.php",
      type: "get",
      dataType: "json",
      async: false,
      data: { user_id: user_id },
      success: (res) => {
        if (res.code == 1) {
          data_cart = res.data;
        }
      },
    });
    return data_cart;
  }

  let cart = localStorage.getItem("cart");
  if (!cart) localStorage.setItem("cart", JSON.stringify([]));
  cart = JSON.parse(localStorage.getItem("cart"));

  const login_state = "LOGIN_STATE";
  let state = getCookie(login_state);
  if (!(state && state == "OK")) {
    if (cart.length > 0) {
      $(".empty-cart-info").text("登录后才能看到商品哦~");
      $(".empty-cart-btn .btn").text("去登陆").attr("href", "./login.html");
    }
    localStorage.setItem("user", "");
    $(".empty-cart").show();
    // $(".cart-info").hide();
  } else {
    setCookie(login_state, "OK", 7 * 24 * 60, "/");
    let user = localStorage.getItem("user");
    if (!user) {
      //数据被删了
      clearCookie(login_state);
      location.reload();
    }
    user = JSON.parse(user);
    userid = user.user_id;
    let data_cart = getCartData(userid);
    cart.forEach((a) => {
      a.user_id = userid;
    });
    localStorage.setItem("cart", JSON.stringify(cart));
    console.log(cart);
    console.log(data_cart);
    if (cart.length == 0 && data_cart.length == 0) {
      $(".empty-cart").show();
    } else {
      $(".empty-cart").hide();
    }

    let edit_cart = []; //数据库需要修改的数据
    let add_cart = cart; //本地需要添加到数据库的数据
    //合并购物车，同步数据库
    cart.forEach((c) => {
      data_cart.forEach((dc) => {
        if (c.goods_id == dc.goods_id) {
          dc.cart_num = dc.cart_num * 1 + c.cart_num;
          dc.total = dc.total * 1 + c.total;
          edit_cart.push(dc);
          add_cart = add_cart.filter((v) => {
            return v.goods_id != dc.goods_id;
          });
        }
      });
    });
    console.log(edit_cart);
    console.log(add_cart);

    function editCart() {
      return $.pajax({
        url: "/api/cart.php",
        type: "post",
        dataType: "json",
        data: { type: "edit", data: JSON.stringify(edit_cart) },
      });
    }
    function addCart() {
      return $.pajax({
        url: "/api/cart.php",
        type: "post",
        dataType: "json",
        data: { type: "add", data: JSON.stringify(add_cart) },
      });
    }
    Promise.all([editCart(), addCart()])
      .then((res) => {
        console.log("同步购物车成功", JSON.stringify(res));
        //同步成功，清空本地购物车数据
        localStorage.setItem("cart", "[]");
        //重新获取所有数据
        let _cart = getCartAndGoodsData(userid);
        //渲染
        console.log(_cart);
        cart_goods_data = _cart;
        renderCart(cart_goods_data);
      })
      .catch((e) => {
        console.warn(e);
      });
  }

  function renderCart(data) {
    if (data.length == 0) return;
    let html = data
      .map((item, index) => {
        return `<div class="item">
              <div class="inps inps-box"><input class="goods_checked" type="checkbox" name="" id="" index="${index}"></div>
              <div class="goods-info">
                  <div class="goods-img"><img src="${item.img}" alt=""></div>
                  <div class="goods-content">
                      <div class="goods-name">${item.goods_name}</div>
                      <div class="goods-price">
                          <span class="new-price"><i>&yen;</i>${
                            item.goods_new_price
                          }</span>
                          <div class="num-group" index="${index}">
                              <span class="reduce ${
                                item.cart_num == 1 ? "disabled" : ""
                              }" max-num="${item.goods_num}"></span>
                              <div class="num">${item.cart_num}</div>
                              <span class="add" ${
                                item.cart_num == item.goods_num
                                  ? "disabled"
                                  : ""
                              } max-num="${item.goods_num}"></span>
                          </div>
                      </div>
                  </div>
              </div>
          </div>`;
      })
      .join("");
    $(".cart-container").html(html);
    $(".cart-info").show();
  }

  function renderNum(el, item) {
    getTotalMoney();
    $(el).parent(".num-group").html(`
      <span class="reduce ${
        item.cart_num == 1 ? "disabled" : ""
      }" max-num="${item.goods_num}"></span>
      <div class="num">${item.cart_num}</div>
      <span class="add" ${
        item.cart_num == item.goods_num ? "disabled" : ""
      } max-num="${item.goods_num}"></span>`);

    let cart = [];
    cart.push({
      cart_id: item.cart_id,
      user_id: item.user_id,
      goods_id: item.goods_id,
      cart_num: item.cart_num,
      total: item.cart_num * item.goods_new_price,
    });

    $.pajax({
      url: "/api/cart.php",
      type: "post",
      dataType: "json",
      data: { type: "edit", data: JSON.stringify(cart) },
    }).then((res) => {
      console.log(res);
    });
  }

  $(document).on("click", ".num-group .reduce", (e) => {
    let index = $(e.target).parent(".num-group").attr("index") * 1;
    if (cart_goods_data[index].cart_num == 1) return;
    if (cart_goods_data[index].cart_num > 1)
      cart_goods_data[index].cart_num -= 1;
    renderNum(e.target, cart_goods_data[index]);
  });

  $(document).on("click", ".num-group .add", (e) => {
    let index = $(e.target).parent(".num-group").attr("index") * 1;
    if (cart_goods_data[index].cart_num == cart_goods_data[index].goods_num)
      return;
    if (cart_goods_data[index].cart_num < cart_goods_data[index].goods_num)
      cart_goods_data[index].cart_num =
        parseInt(cart_goods_data[index].cart_num) + 1;
    renderNum(e.target, cart_goods_data[index]);
  });

  function getCartAndGoodsData(user_id) {
    let dataset = [];
    $.ajax({
      url: "/api/cart.php",
      type: "get",
      dataType: "json",
      async: false,
      data: { user_id: user_id, type: "all" },
      success: (res) => {
        if (res.code == 1) {
          dataset = res.data;
        }
      },
    });
    return dataset;
  }

  $.pajax({
    url: "/api/goods.php",
    type: "get",
    dataType: "json",
    data: { type: "cart" },
  }).then((res) => {
    if (res.code == 1) {
      let html = res.data
        .map((item) => {
          return `<div class="item" goods-id="${item.goods_id}">
                    <div class="goods-img">
                        <img class="lazy" data-original="${item.img}" alt="${item.goods_name}">
                    </div>
                    <div class="goods-name">${item.goods_name}</div>
                    <div class="goods-poster">${item.goods_poster}</div>
                    <div class="goods-pirce">
                        <span class="new-price"><i>&yen;</i>${item.goods_new_price}</span>
                        <span class="old-price"><i>&yen;</i>${item.goods_price}</span>
                    </div>
                    <div class="goods-type"><span class="type">${item.type}</span></div>
                </div>`;
        })
        .join("");
      $(".shoplist").html(html);
      $("img.lazy").lazyload({ effect: "fadeIn" });
    }
  });

  $(".content .shoplist").on("click", ".item", (e) => {
    let goods_id = $(e.target).attr("goods-id");
    if (goods_id) location.href = "../html/detail.html?goods_id=" + goods_id;
  });

  $(".all_checked").click(function () {
    let allChecked = $(this).is(":checked");
    $(".goods_checked").each(function () {
      $(this).prop("checked", allChecked);
    });
    getTotalMoney();
  });

  $(document).on("click", ".goods_checked", (e) => {
    let flag = Array.from($(".goods_checked")).every((v, i) => {
      return v.checked;
    });
    $(".all_checked").prop("checked", flag);
    getTotalMoney();
  });

  function getTotalMoney() {
    let data = getSelectData();
    let totalMeony = data.reduce((pre, item) => {
      return pre + item.total * 1;
    }, 0);
    $(".totalMoney").text(totalMeony);
    return totalMeony;
  }

  $(".del").click(function () {
    let data = getSelectData();
    let cart_ids = data
      .map((item) => {
        return item.cart_id;
      })
      .join(",");
    console.log(cart_ids);
    $.pajax({
      url: "/api/cart.php",
      type: "post",
      dataType: "json",
      data: { type: "del", cart_ids: cart_ids },
    }).then((res) => {
      location.reload();
    });
  });
  $(".jiesuan").click(function () {
    let data = getSelectData();
    let total = getTotalMoney();
    if (total == 0 || data.length == 0) return;

    let order = {
      user_id: data[0].user_id,
      total: total,
      data: data,
    };
    sessionStorage.setItem("order", JSON.stringify(order));
    location.href = "../html/order.html";
  });

  function getSelectData() {
    let selectData = [];
    $(".goods_checked").each(function () {
      if ($(this).is(":checked")) {
        let index = $(this).attr("index") * 1;
        let item = cart_goods_data[index];
        let obj = {
          cart_id: item.cart_id,
          user_id: item.user_id,
          goods_id: item.goods_id,
          cart_num: item.cart_num,
          total: item.cart_num * item.goods_new_price,
          img: item.img,
          name: item.goods_name,
          price: item.goods_new_price,
        };
        selectData.push(obj);
      }
    });
    return selectData;
  }
});
